package com.myfojing.mycloud;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Locale;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

import io.realm.Realm;


public class DiscoveryActivity extends AppCompatActivity {

    private final String TAG = "我的发现";
    DiscoveryListviewAdapter adapter;
    private WifiManager.MulticastLock multicastLock;
    private ListView listView;
    private TextView local_ip;
    private Handler handler;
    private String serviceType = "_nodemcu._tcp.local.";
    private JmDNS jmdns;
    private ServiceListener listener;
    private ServiceInfo serviceInfo;
    private int mPosition = 0;
    // 扫描结果
    private ArrayList<Sensirion> list;
    private String ip_config;
    private String port_config;
    // 增加新节点
    private int count_save;

    // 接收wifi变化广播
    private WiFiStateReceiver receiver = new WiFiStateReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discovery);

        // ui
        count_save = 0;

        listView = (ListView) findViewById(R.id.lvScanResult);
        listView.addHeaderView(getLayoutInflater().inflate(R.layout.discovery_listview_header,
                null, false));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    view.setSelected(true);
                    mPosition = position;
                }
            }
        });
        local_ip = (TextView) findViewById(R.id.discovery_local_ip);

        handler = new Handler();

        list = new ArrayList<>();
        adapter = new DiscoveryListviewAdapter(this, list);
        listView.setAdapter(adapter);

        // 接收广播
        receiver = new WiFiStateReceiver();
        receiver.setListener(new WiFiStateReceiver.WiFiStateListener() {
            @Override
            public void change_ip(String address) {
                //Log.d(TAG, address.toString());
                local_ip.setText(address);
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.wifi.STATE_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (multicastLock != null) {
            multicastLock.release();
            try {
                jmdns.unregisterAllServices();
                jmdns.close();
            } catch (IOException | NullPointerException e) {
                e.printStackTrace();
            }

            jmdns = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (count_save > 0) {
            count_save = 0;
            setResult(RESULT_OK);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }

    /*  用户定义函数 */
    // 扫描按钮
    public void onScanClick(View view) {
        // 是否网络内扫描
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();

        final String server_ip = WiFiStateReceiver.intToIp(dhcpInfo.serverAddress);
        Sensirion sensirion = new Sensirion(server_ip, "80");
        sensirion.read_all();

        sensirion.setSensirionListener(new Sensirion.SensirionListener() {
            @Override
            public void onDataReady(JSONObject data) {
                try {
                    if (data.getBoolean("success")) {
                        if (data.getString("cmd").equals("read_all")) {
                            display_one_sensirion(new_sensirion(data));
                        }
                    } else {
                        jmdns();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });
    }

    // 配置按钮
    public void onConfigClick(View view) {
        Intent intent = new Intent(this, ConfigActivity.class);
        // listview 选中
        Sensirion sensirion = (Sensirion) listView.getItemAtPosition(mPosition);
        if (sensirion != null) {
            intent.putExtra("sensirion", sensirion);
            intent.putExtra("ip_config", sensirion.getIp());
            intent.putExtra("port_config", sensirion.getPort());
            startActivity(intent);
        }
    }

    // 保存按钮
    public void onSaveClick(View view) {
        final Sensirion sensirion = (Sensirion) listView.getItemAtPosition(mPosition);
        if (sensirion != null) {
            sensirion.read_all();
            sensirion.setSensirionListener(new Sensirion.SensirionListener() {
                @Override
                public void onDataReady(JSONObject data) {
                    Realm realm = Realm.getDefaultInstance();
                    try {
                        Sensirion sensirion = new_sensirion(data);
                        SensirionHelper.save_or_update(sensirion, realm);
                        count_save++;
                    } finally {
                        realm.close();
                    }
                }
            });

        }
    }

    // 获得IP
    private InetAddress getLocalIpAddress() {
        WifiManager wifiManager = (WifiManager) getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        InetAddress address = null;
        try {
            address = InetAddress.getByName(String.format(Locale.ENGLISH, "%d.%d.%d.%d",
                    (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address;
    }

    private void jmdns() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WifiManager wifiManager = (WifiManager) getApplicationContext()
                        .getSystemService(Context.WIFI_SERVICE);
                multicastLock = wifiManager.createMulticastLock(getClass().getName());
                multicastLock.setReferenceCounted(false);
                try {
                    final InetAddress inetAddress = getLocalIpAddress();
                    multicastLock.acquire();
                    jmdns = JmDNS.create(inetAddress, "Observer");
                    listener = new ServiceListener() {
                        @Override
                        public void serviceAdded(ServiceEvent event) {
                            jmdns.requestServiceInfo(event.getType(),
                                    event.getName(), 1000);
                        }

                        @Override
                        public void serviceRemoved(ServiceEvent event) {
                            Log.d(TAG, "服务移除: " + event.getName());
                        }

                        @Override
                        public void serviceResolved(ServiceEvent event) {
                            Log.d(TAG, "服务分析: " + event.getInfo().getQualifiedName() + " port:" + event.getInfo().getPort());
                            //Log.e(LOGTAG, "服务类型 : " + event.getInfo().getType());
                            serviceInfo = event.getInfo();

                            // 数据
                            //String name = serviceInfo.getName();
                            // 是否已经存在
                            InetAddress inetAddress_1 = serviceInfo.getInet4Addresses()[0];
                            String ip = inetAddress_1.getHostAddress();
                            String nm = serviceInfo.getPropertyString("netmask");
                            String mac = serviceInfo.getPropertyString("mac");

                            display_one_sensirion(ip, nm, Integer.toString(serviceInfo.getPort()), mac);
                        }
                    };

                    jmdns.addServiceListener(serviceType, listener);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 显示一个传感器
    private void display_one_sensirion(String ip, String nm, String port, String mac) {
        Sensirion model = new Sensirion();
        model.setIp(ip);
        model.setNm(nm);
        model.setPort(port);
        model.setMac(mac);
        list.add(model);
        handler.post(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void display_one_sensirion(Sensirion sensirion) {
        list.add(sensirion);
        handler.post(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    private Sensirion new_sensirion(JSONObject data) {
        Sensirion sensirion = new Sensirion();
        try {
            JSONObject network = data.getJSONObject("network");
            JSONObject device = data.getJSONObject("device");
            sensirion.setIp(network.getString("ip"));
            sensirion.setNm(network.getString("netmask"));
            sensirion.setGw(network.getString("gateway"));
            sensirion.setPort(network.getString("port"));
            sensirion.setMac(network.getString("mac"));

            sensirion.setTitle(device.getString("title"));
            sensirion.setDescription(device.getString("desc"));
            sensirion.setType(device.getString("type"));
            sensirion.setPIN(device.getString("PIN"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return sensirion;
    }

    // end
}
